<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { queryMenuPermission, queryPermissionIdsWithRoleId, add } from '@/service/api/system-manage';
import { useBoolean } from '@sa/hooks';

defineOptions({
  name: 'DhkPermissionDialog'
});

interface Props {
  visible: boolean;
  roleId: number;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:visible', 'close', 'success']);

const { bool: loading, setTrue: startLoading, setFalse: stopLoading } = useBoolean(false);
const { bool: fetchError, setTrue: setFetchError, setFalse: clearFetchError } = useBoolean(false);
const menuCategories = ref([]);
const checkedPermissionIds = ref([]);

const show = computed({
  get: () => props.visible,
  set: value => {
    emit('update:visible', value);
    if (!value) {
      emit('close');
    }
  }
});

watch(() => props.visible, value => {
  if (value && props.roleId) {
    clearFetchError();
    refreshData();
  }
});

async function loadMenuPermissions() {
  loading.value = true;
  fetchError.value = false;

  try {
    const res = await queryMenuPermission();
    if (res?.data) {
      menuCategories.value = Array.isArray(res.data) ? res.data : [];
      console.log('Menu permissions loaded:', menuCategories.value.length, 'menus');
    } else {
      console.error('Failed to load menu permissions: No data');
      fetchError.value = true;
    }
  } catch (error) {
    console.error('Failed to load menu permissions:', error);
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

async function loadCheckedPermissions() {
  if (!props.roleId) return;

  const roleId = Number(props.roleId);
  loading.value = true;

  try {
    const res = await queryPermissionIdsWithRoleId(roleId);
    checkedPermissionIds.value = Array.isArray(res?.data)
      ? res.data.map(id => Number(id)).filter(Boolean)
      : [];
    console.log('Checked permissions loaded:', checkedPermissionIds.value.length, 'items');
  } catch (error) {
    console.error('Failed to load role permissions:', error);
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

function refreshData() {
  checkedPermissionIds.value = [];
  menuCategories.value = [];
  loadMenuPermissions();
  loadCheckedPermissions();
}

function isChecked(id) {
  return checkedPermissionIds.value.includes(id);
}

function togglePermission(id) {
  if (isChecked(id)) {
    checkedPermissionIds.value = checkedPermissionIds.value.filter(i => i !== id);
  } else {
    checkedPermissionIds.value.push(id);
  }
}

function closeDialog() {
  emit('update:visible', false);
  emit('close');
}

async function handleSubmit() {
  if (!props.roleId) {
    ElMessage.warning('请选择角色');
    return;
  }

  loading.value = true;
  
  try {
    const params = {
      roleId: Number(props.roleId),
      permissionIds: checkedPermissionIds.value
    };

    await add(params);
    ElMessage.success('权限更新成功');
    emit('success');
    closeDialog();
  } catch (error) {
    console.error('提交权限配置失败:', error);
    ElMessage.error('提交失败');
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <el-dialog
    v-model="show"
    title="编辑按钮权限"
    width="800px"
    destroy-on-close
    @closed="closeDialog"
  >
    <div v-loading="loading" class="permission-container">
      <div v-if="fetchError" class="flex-center h-full">
        <div class="text-center">
          <div class="text-red-500 text-xl mb-4">操作失败</div>
          <div class="mb-4">获取权限数据失败，请刷新重试</div>
          <el-button type="primary" @click="refreshData">重新加载</el-button>
        </div>
      </div>

      <div v-else>
        <!-- Menu Categories and Permissions -->
        <div class="category-section">
          <!-- Category Headers -->
          <div class="category-header">
            <div class="menu-column">菜单分类</div>
            <div class="permissions-column">可用权限</div>
          </div>
          
          <!-- Category Items -->
          <div v-for="menu in menuCategories" :key="menu.menuId" class="category-row">
            <!-- Parent Menu -->
            <div class="menu-column parent-menu">{{ menu.menuName || '未命名菜单' }}</div>
            
            <!-- Parent Permissions -->
            <div class="permissions-column">
              <el-checkbox 
                v-for="button in menu.buttons || []" 
                :key="button.id"
                :model-value="isChecked(button.id)"
                @change="() => togglePermission(button.id)"
                class="permission-checkbox"
              >
                {{ button.description || button.name }}
              </el-checkbox>
            </div>
          </div>
          
          <!-- Child menus and their permissions -->
          <template v-for="parent in menuCategories" :key="parent.menuId + '-children'">
            <div v-for="child in parent.children || []" :key="child.menuId" class="category-row child-row">
              <!-- Child Menu -->
              <div class="menu-column child-menu">{{ child.menuName || '未命名子菜单' }}</div>
              
              <!-- Child Permissions -->
              <div class="permissions-column">
                <el-checkbox 
                  v-for="button in child.buttons || []" 
                  :key="button.id"
                  :model-value="isChecked(button.id)"
                  @change="() => togglePermission(button.id)"
                  class="permission-checkbox"
                >
                  {{ button.description || button.name }}
                </el-checkbox>
                
                <!-- Show empty message if no permissions -->
                <span v-if="(child.buttons || []).length === 0" class="no-permissions">
                  该菜单暂无可配置权限
                </span>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.permission-container {
  height: 600px;
  overflow: auto;
}

.category-section {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.category-header {
  display: flex;
  background-color: #f5f7fa;
  font-weight: bold;
  border-bottom: 1px solid #dcdfe6;
}

.menu-column {
  width: 200px;
  padding: 12px 15px;
  border-right: 1px solid #dcdfe6;
}

.permissions-column {
  flex: 1;
  padding: 12px 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.category-row:hover {
  background-color: #f5f7fa;
}

.parent-menu {
  font-weight: bold;
  background-color: #f0f2f5;
}

.child-row {
  background-color: #fafafa;
}

.child-menu {
  padding-left: 30px;
}

.permission-checkbox {
  margin-right: 15px;
  margin-bottom: 5px;
}

.no-permissions {
  color: #909399;
  font-style: italic;
}

/* Utilities */
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.h-full {
  height: 100%;
}

.flex {
  display: flex;
}

.justify-end {
  justify-content: flex-end;
}

.text-center {
  text-align: center;
}

.text-red-500 {
  color: #f56c6c;
}

.text-xl {
  font-size: 1.25rem;
}

.mb-4 {
  margin-bottom: 1rem;
}
</style> 